<template>
	<div class="bg-white dark:bg-zinc-900 sticky top-0 left-0 z-10 duration-500">
		<ul
			ref="ulTarget"
			class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
		>
			<!-- 滑块 -->
			<li
				ref="sliderTarget"
				:style="sliderStyle"
				class="absolute h-[22px] bg-zinc-900 dark:bg-zinc-800 rounded-lg duration-200"
			></li>

			<!-- 汉堡按钮 -->
			<li
				@click="onShowPopup"
				class="fixed top-0 right-[-1px] h-4 px-1 flex items-center dark:bg-zinc-900 bg-white z-20 shadow-l-white dark:shadow-l-zinc"
			>
				<m-svg-icon class="w-1.5 h-1.5" name="hamburger"></m-svg-icon>
			</li>

			<!-- items-->
			<li
				class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
				v-for="(item, index) in $store.getters.categorys"
				:key="item.id"
				:ref="setItemRef"
				:class="{
					'text-zinc-100': $store.getters.currentCategoryIndex === index,
				}"
				@click="onItemClick(item, index)"
			>
				{{ item.name }}
			</li>
		</ul>

		<m-popup v-model="isVisible">
			<menu-vue @onItemClick="onItemClick"></menu-vue>
		</m-popup>
	</div>
</template>

<script setup>
import { onBeforeUpdate, ref, watch } from 'vue'
import { useScroll } from '@vueuse/core'
import MenuVue from '@/views/main/components/menu/index.vue'
import { useStore } from 'vuex'

const store = useStore()

const sliderStyle = ref({
	transform: 'translateX(0px)',
	width: '48px',
})

// 获取所有的item元素
let itemRefs = []
const setItemRef = (el) => {
	if (el) {
		itemRefs.push(el)
	}
}

// 数据改变之后，Dom变化之前
onBeforeUpdate(() => {
	itemRefs = []
})

// 获取ul元素
const ulTarget = ref(null)
const { x: ulScrollLeft } = useScroll(ulTarget)

watch(
	() => store.getters.currentCategoryIndex,
	(val) => {
		const { left, width } = itemRefs[val].getBoundingClientRect()

		sliderStyle.value = {
			transform: `translateX(${ulScrollLeft.value + left - 10}px)`,
			width: width + 'px',
		}
	}
)

const onItemClick = (item, index) => {
	itemRefs[index].scrollIntoView({
		behavior: 'smooth',
		inline: 'center',
	})
	store.commit('app/changeCurrentCategory', item)
	isVisible.value = false
}

// 控制popup展示
const isVisible = ref(false)

const onShowPopup = () => {
	isVisible.value = true
}
</script>
